package com.hpq.common.service;

import com.hpq.common.exception.BusinessException;
import com.hpq.common.exception.HttpStatusEnum;
import lombok.SneakyThrows;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;

/**
 * 分布式锁服务
 * @author hpq
 *
 */
@Service
public class LockService {
    @Autowired
    private RedissonClient redissonClient;
    /**
     *  获取锁
     * @param lockKey
     * @param waitTime
     * @param timeUnit
     * @param supplier
     * @return
     * @param <T>
     */
    public <T> T executeByLock(String lockKey, int waitTime , TimeUnit timeUnit, SupplierThrow<T> supplier) throws Throwable{
        RLock lock = redissonClient.getLock(lockKey);
        boolean success = lock.tryLock(waitTime, timeUnit);
        if(!success){
            throw new BusinessException(HttpStatusEnum.LOCK_LIMIT);
        }
        try {
            return supplier.get();
        }finally {
            lock.unlock();
        }
    }

    /**
     *  获取锁，默认等待时间，supplier实现
     * @param lockKey
     * @param supplier
     * @return
     * @param <T>
     */

    @SneakyThrows
    public <T> T executeByLock(String lockKey, Supplier<T> supplier) {
        return executeByLock(lockKey,-1,TimeUnit.MILLISECONDS,supplier::get);
    }

    /**
     *  获取锁，默认等待时间,runnable实现
     * @param lockKey
     * @param runnable
     * @return
     * @param <T>
     */

    @SneakyThrows
    public <T> T executeByLock(String lockKey,Runnable runnable) {
        return executeByLock(lockKey,-1,TimeUnit.MILLISECONDS,()->{
            runnable.run();
            return null;
        });
    }
    @FunctionalInterface
    public interface SupplierThrow<T> {

        /**
         * Gets a result.
         * @return a result
         */
        T get() throws Throwable;
    }


}
